﻿using CalligraphyWeb.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using ThuPhap.Models;

namespace CalligraphyWeb
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "calligraphy" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select calligraphy.svc or calligraphy.svc.cs at the Solution Explorer and start debugging.
    public class calligraphy : Icalligraphy
    {
        public string DoWork()
        {
            return "test"; 
        }

        public ObservableCollection<TemplateThumbnail> GetOnlineTemplateItems()
        {
            string domain = HttpContext.Current.Request.Url.Scheme + System.Uri.SchemeDelimiter + 
                HttpContext.Current.Request.Url.Host + (HttpContext.Current.Request.Url.IsDefaultPort ? "" : ":" + HttpContext.Current.Request.Url.Port);
            ObservableCollection<TemplateThumbnail> result = new ObservableCollection<TemplateThumbnail>();

            var templates = Calligraphy.Models.Template.Get(isLazy: false);

            foreach (var iter in templates)
            {
                var temp = new TemplateThumbnail()
                {
                    ID = iter.id,
                    Name = iter.name,
                    Description = iter.description,
                    Date = iter.updated.Value,
                    Thumbnail = domain +  "/Data/TemplateImages/" + iter.thumbnail,
                    UserID = iter.userid.Value,
                    Username = iter.user.username
                };
                result.Add(temp);
            }

            return result;
        }

        public byte[] GetOnlineTemplate(int id)
        {
            MemoryStream stream = new MemoryStream();
            var xmlSerializer = new XmlSerializer(typeof(Template));
            var template = new Calligraphy.Models.Template(id, false);

            xmlSerializer.Serialize(stream, template.ToPhoneTemplate());

            return stream.ToArray(); ;
        }
    }
}
